package com.chinaums.xm.wechat.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author chenjf
 *
 */
@Service
public class Communicator {

	private static final Logger logger = LoggerFactory.getLogger(Communicator.class);

	private CloseableHttpClient httpClient;

	@PostConstruct
	public void init() {
		final HttpClientBuilder httpClientBuilder = HttpClients.custom().setMaxConnPerRoute(50).setMaxConnTotal(100)
				.setDefaultRequestConfig(
						RequestConfig.custom().setConnectTimeout(60 * 1000).setSocketTimeout(60 * 1000).build())
				.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());
		httpClient = httpClientBuilder.build();
	}

	@PreDestroy
	public void destroy() throws IOException {
		httpClient.close();
	}

	public Optional<String> getRequest(String url) {
		logger.info("get请求地址：{}", url);
		final HttpGet get = new HttpGet(url);
		try (final CloseableHttpResponse response = httpClient.execute(get)) {
			final HttpEntity responseEntity = response.getEntity();
			final String responseMsg = EntityUtils.toString(responseEntity, "UTF-8");
			logger.info("get响应报文：{}", responseMsg);
			return Optional.of(responseMsg);
		} catch (Exception e) {
			return Optional.empty();
		}
	}
	/**
	 * 
	 * 获取图片或者二维码
	 * @param url
	 * @param localPath 本地地址
	 */
	public void getImageRequest(String url,final String localPath) {
		logger.info("get请求地址：{}", url);
		final HttpGet get = new HttpGet(url);
		try (final CloseableHttpResponse response = httpClient.execute(get)) {
			final InputStream in = response.getEntity().getContent();
			IOUtils.copy(in, new FileOutputStream(new File(localPath)));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
	}

	public Optional<String> postRequest(String url, String params) {
		logger.info("post请求地址：{}", url);
		logger.info("post请求参数：{}", params);
		final HttpPost post = new HttpPost(url);
		final StringEntity requestEntity = new StringEntity(params, "UTF-8");
		post.setEntity(requestEntity);
		try (final CloseableHttpResponse response = httpClient.execute(post)) {
			final HttpEntity responseEntity = response.getEntity();
			final String responseMsg = EntityUtils.toString(responseEntity, "UTF-8");
			return Optional.of(responseMsg);
		} catch (Exception e) {
			return Optional.empty();
		}
	}
}
